package gui;

import API_Jung.PopupVertexEdgeMenuMousePlugin;
import API_Jung.MyMouseMenus;
import edu.uci.ics.jung.algorithms.layout.KKLayout;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.visualization.FourPassImageShaper;
import edu.uci.ics.jung.visualization.LayeredIcon;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.EllipseVertexShapeTransformer;
import edu.uci.ics.jung.visualization.decorators.VertexIconShapeTransformer;
import edu.uci.ics.jung.visualization.renderers.DefaultEdgeLabelRenderer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import metodologia.Aresta;
import metodologia.ConjuntoDeEtapas;
import metodologia.DadosMetodologia;
import metodologia.SerializarObjetoCryptografado;
import metodologia.TestNode;
import metodologia.Teste;
import metodologia.ToDoNode;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;

public class JanelaAbrirMetodologia extends javax.swing.JFrame implements java.io.Serializable{

    private int nodetype, nodecount, nTests, nEdges;
    private DirectedSparseGraph<TestNode, String> g; // Grafo usado na criação de uma nova metodologia
    private DirectedSparseGraph<TestNode, String> g1;  // Grafo usado quando se carrega uma metodologia
    private DirectedSparseGraph<ToDoNode, String> g2; // Grafo usado pra carregar os dados das etapas
    private TestNode start; // Primeiro nó do grafo
    private SerializarObjetoCryptografado<DadosMetodologia> objeto; // Objeto usado para serializar os dados
    private VisualizationViewer<TestNode, String> vv;
    private DadosMetodologia dadosMetodologia; // Todos os dados da metodologia
    private KKLayout<TestNode, String> layout;
    private JScrollPane graphScroll;
    private ArrayList<Aresta> listaDasArestasDosTestes;
    private ArrayList<TestNode> listadetestes;

    /** Creates new form MetodologiadeTestes */
    public JanelaAbrirMetodologia(DadosMetodologia dadosMetodologia) throws Exception {
        initComponents();
        this.dadosMetodologia = dadosMetodologia;
        
        this.setTitle("PWManager - " + dadosMetodologia.getNome());
        this.setLocationRelativeTo(null);
        ImageIcon imagemTituloJanela = new ImageIcon(getClass().getResource("/ImageFiles/icon_PW.png"));  
        setIconImage(imagemTituloJanela.getImage());
        nodetype = 0;
        nodecount = 0;
        nTests = 1;
        nEdges = 1;
        listadetestes = new ArrayList<TestNode>();
        createGraphScreen();
        
        this.setMinimumSize(new Dimension(750,450));
        objeto = new SerializarObjetoCryptografado<DadosMetodologia>();
        listaDasArestasDosTestes = new ArrayList<Aresta>();
        jmSalvar.setVisible(false);
        jSeparator2.setVisible(false);
        this.setTitle("PWManager" + this.dadosMetodologia.getNome() + 
                " | Autor: " + this.dadosMetodologia.getAutor() + 
                " | Versão: " + this.dadosMetodologia.getVersao());
    }

    public final void zerarToolbar() {        
        //System.out.println("Entrou no zerarToolbar | g = " + g1.getVertexCount());
        for(Iterator i = g1.getVertices().iterator(); i.hasNext();){
            TestNode teste = (TestNode)i.next();
            teste.getTodoscreen().zerarToolbar(false);
            teste.getTodoscreen().setGraphMouse();
            //System.out.println("zerou o toolbar do nó " + teste.getId());
        }
    }
    
    public final void createGraphScreen() {
        JTabbedPane GraphS = new JTabbedPane();
        
        g = new DirectedSparseGraph<TestNode, String>();
        g1 = new DirectedSparseGraph<TestNode, String>();
        
        layout = new KKLayout(g);
        layout.setSize(new Dimension(300, 300));

        vv = new VisualizationViewer<TestNode, String>(layout);
        vv.setPreferredSize(new Dimension(300, 300));
        vv.setBackground(Color.WHITE);
        // Show vertex and edge labels

        vv.getRenderContext().setVertexLabelTransformer(new Transformer<TestNode, String>() {

            @Override
            public String transform(TestNode v) {
                switch (v.getType()) {
                    case 0:
                        return "Start";
                    case 1:
                        return "End";
                    case 2:
                        return "Test" + " " + v.getCatid();
                }
                return "Start";
            }
        });

        vv.getRenderContext().setEdgeLabelTransformer(new Transformer<String, String>() {

            @Override
            public String transform(String e) {
                return "";
            }
        });

        vv.getRenderContext().setVertexIconTransformer(
                new MyVertexIconTransformer<TestNode>());
        vv.getRenderContext().setVertexShapeTransformer(
                new MyVertexIconShapeTransformer<TestNode>(new EllipseVertexShapeTransformer<TestNode>()));
        vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.cyan));
        vv.setVertexToolTipTransformer(vv.getRenderContext().getVertexLabelTransformer());


        Factory<TestNode> vertexFactory = new VertexFactory();
        Factory<String> edgeFactory = new EdgeFactory();

        final EditingModalGraphMouse<TestNode, String> graphMouse =
                new EditingModalGraphMouse<TestNode, String>(vv.getRenderContext(), vertexFactory, edgeFactory);

        PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
        // Add some popup menus for the edges and vertices to our mouse plugin.
        JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu();
        JPopupMenu EdgeMenu = new MyMouseMenus.EdgeMenu();

        myPlugin.setVertexPopup(vertexMenu);
        myPlugin.setEdgePopup(EdgeMenu);
        graphMouse.remove(graphMouse.getPopupEditingPlugin());  // Removes the existing popup editing plugin

        graphMouse.add(myPlugin);   // Add our new plugin to the mouse

        vv.setGraphMouse(graphMouse);
        vv.addKeyListener(graphMouse.getModeKeyListener());

        graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
//        this.jComboBox1.setModel(graphMouse.getModeComboBox().getModel());

        graphScroll = new JScrollPane(vv);
        graphScroll.setSize(this.GraphScreen.getSize());

        //GraphS.addTab("Testes", graphScroll);


        GraphScreen.setLayout(new BorderLayout());
        // GraphScreen.add("Center", GraphS);
        GraphScreen.add("Center", graphScroll);
        
        //Collection<TestNode> col = g.getVertices();
        if (!dadosMetodologia.getListaDeTestes().isEmpty()) {
            reloadGraphScreen();
        }
    }

    public class MyVertexIconTransformer<TestNode> implements Transformer<TestNode, Icon> {

        @Override
        public Icon transform(TestNode n) {
            String[] n2 = n.toString().split("a");
            String[] n3 = n.toString().split("n");

            if (n2.length > 1) {
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/StartBall.png")).getImage());
                return icon;
            } else if (n3.length > 1) {
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/EndNode.png")).getImage());
                return icon;
            } else {
                for (Iterator it = g.getEdges().iterator(); it.hasNext();) {
                    String edge = (String) it.next();

                    if (g.getEndpoints(edge).getFirst().toString().equals(n.toString()) && g.getEndpoints(edge).getSecond().toString().equals(start.toString())) {
                        Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/targetBall.png")).getImage());
                        return icon;
                    } else if (g.getEndpoints(edge).getSecond().toString().equals(n.toString()) && g.getEndpoints(edge).getFirst().toString().equals(start.toString())) {
                        Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/targetBall.png")).getImage());
                        return icon;
                    }
                }
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/TestNode.png")).getImage());
                return icon;
            }
        }
    }
    
    public class MyVertexIconTransformerLoadGraph<TestNode> implements Transformer<TestNode, Icon> {

        @Override
        public Icon transform(TestNode n) {
            String[] n2 = n.toString().split("a");
            String[] n3 = n.toString().split("n");

            if (n2.length > 1) {
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/StartBall.png")).getImage());
                return icon;
            } else if (n3.length > 1) {
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/EndNode.png")).getImage());
                return icon;
            } else {
                for (Iterator it = g1.getEdges().iterator(); it.hasNext();) {
                    String edge = (String) it.next();

                    if (g1.getEndpoints(edge).getFirst().toString().equals(n.toString()) && g1.getEndpoints(edge).getSecond().toString().equals(start.toString())) {
                        Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/targetBall.png")).getImage());
                        return icon;
                    } else if (g1.getEndpoints(edge).getSecond().toString().equals(n.toString()) && g1.getEndpoints(edge).getFirst().toString().equals(start.toString())) {
                        Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/targetBall.png")).getImage());
                        return icon;
                    }
                }
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/TestNode.png")).getImage());
                return icon;
            }
        }
    }

    public static class MyVertexIconShapeTransformer<TestNode> extends VertexIconShapeTransformer<TestNode> {

        boolean shapeImages = true;

        public MyVertexIconShapeTransformer(Transformer<TestNode, Shape> delegate) {
            super(delegate);
        }

        public boolean isShapeImages() {
            return shapeImages;
        }

        public void setShapeImages(boolean shapeImages) {
            shapeMap.clear();
            this.shapeImages = shapeImages;
        }

        public Icon getIcon(TestNode n) {
            String[] n2 = n.toString().split("a");
            String[] n3 = n.toString().split("n");
            if (n2.length > 1) {
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/StartBall.png")).getImage());
                return icon;
            } else if (n3.length > 1) {
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/EndNode.png")).getImage());
                return icon;
            } else {
                Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/TestNode.png")).getImage());
                return icon;
            }
        }

        @Override
        public Shape transform(TestNode v) {
            Icon icon = getIcon(v);

            if (icon != null && icon instanceof ImageIcon) {

                Image image = ((ImageIcon) icon).getImage();

                Shape shape = shapeMap.get(image);
                if (shape == null) {
                    if (shapeImages) {
                        shape = FourPassImageShaper.getShape(image, 30);
                    } else {
                        shape = new Rectangle2D.Float(0, 0,
                                image.getWidth(null), image.getHeight(null));
                    }
                    if (shape.getBounds().getWidth() > 0
                            && shape.getBounds().getHeight() > 0) {
                        int width = image.getWidth(null);
                        int height = image.getHeight(null);
                        AffineTransform transform =
                                AffineTransform.getTranslateInstance(-width / 2, -height / 2);
                        shape = transform.createTransformedShape(shape);
                        shapeMap.put(image, shape);
                    }
                }
                return shape;
            } else {
                return delegate.transform(v);
            }
        }
    }

    class VertexFactory implements Factory<TestNode> {

        @Override
        public TestNode create() {
            switch (nodetype) {
                case 0:
                    System.out.println("nodetype = " + nodetype);
                    start = new TestNode(nodecount++, nodetype, 0);
                    return start;
                case 1:
                    System.out.println("nodetype = " + nodetype);
                    return new TestNode(nodecount++, nodetype, 0);
                case 2:
                    System.out.println("nodetype = " + nodetype);
                    return new TestNode(nodecount++, nodetype, nTests++);
            }
            return new TestNode(nodecount++, nodetype, 0);
        }
    }

    class EdgeFactory implements Factory<String> {

        @Override
        public String create() {
            return "" + nEdges++;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        fileChooser = new javax.swing.JFileChooser();
        GraphScreen = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jmMenu = new javax.swing.JMenu();
        jmSalvar = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(GraphScreen, java.awt.BorderLayout.CENTER);

        jmMenu.setText("Arquivo");

        jmSalvar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jmSalvar.setText("Salvar");
        jmMenu.add(jmSalvar);
        jmMenu.add(jSeparator2);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
        jMenuItem1.setText("Cancelar");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jmMenu.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/sair16x16.png"))); // NOI18N
        jMenuItem2.setText("Sair");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jmMenu.add(jMenuItem2);

        jMenuBar1.add(jmMenu);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

        
        
        int n = 0;
        
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        try {
            JanelaPrincipal janela = new JanelaPrincipal();
            this.setVisible(false);
            janela.setVisible(true);
        } catch (Exception ex) {
            Logger.getLogger(JanelaAbrirMetodologia.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(JanelaTestes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(JanelaTestes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(JanelaTestes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(JanelaTestes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                try {
//                    new JanelaTestes().setVisible(true);
//                } catch (Exception ex) {
//                    Logger.getLogger(JanelaTestes.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel GraphScreen;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JMenu jmMenu;
    private javax.swing.JMenuItem jmSalvar;
    // End of variables declaration//GEN-END:variables
 
    // Função para carregar a lista de arestas dos testes. Funcionando corretamente
    private void carregarListaDeArestaDosTestes(){
        DirectedSparseGraph<TestNode, String> gTeste;
        if(g1.getVertices().isEmpty()){
            gTeste = g;
        }else{
            gTeste = g1;
        }
        for(Iterator itt = gTeste.getEdges().iterator(); itt.hasNext();){
            Object object = itt.next();
            
            String edge_teste = (String)object;
            
            TestNode origem = gTeste.getSource(edge_teste);
            TestNode destino = gTeste.getDest(edge_teste);
            
            listaDasArestasDosTestes.add(new Aresta(edge_teste, origem.getId(), destino.getId()));
        }
    }
    
    // Função para carregar a llista de arestas das etapas. Funcionando corretamente
    private ArrayList<Aresta> carregarListaDeArestaDasEtapas(DirectedSparseGraph<ToDoNode, String> g1) {
        ArrayList<Aresta> lista = new ArrayList<Aresta>();
        for(Iterator itt = g1.getEdges().iterator(); itt.hasNext();){
            Object object = itt.next();
            
            String edge_etapa = (String)object;
            
            ToDoNode origem = g1.getSource(edge_etapa);
            ToDoNode destino = g1.getDest(edge_etapa);
            
            lista.add(new Aresta(edge_etapa, origem.getId(), destino.getId()));
            System.out.print(edge_etapa + "[" + origem.getId() + "," + destino.getId() + "], ");
        }
        return lista;
    }
    
    // Colocar os dados do grafo em dadosMetodologia
    // Dados dos testes ok
    // Dados das etapas ok
    private void carregarDados(){
        DirectedSparseGraph<TestNode, String> gTeste;
        if(g1.getVertices().isEmpty()){
            gTeste = g;
        }else{
            gTeste = g1;
        }
        // Atualizar a posição de cada vértice
        for (Iterator it = gTeste.getVertices().iterator(); it.hasNext();) {
                TestNode object = (TestNode) it.next();
                object.setX(layout.getX(object));
                object.setY(layout.getY(object));
            }
        
        boolean cont1 = true;
        
        ArrayList<Teste> listaDeTestes = new ArrayList<Teste>();
        ArrayList<ConjuntoDeEtapas> listaConjuntoDeEtapas;
        
        // Percorre todos os vértices de testes
        for(Iterator itt = gTeste.getVertices().iterator(); itt.hasNext();){
            TestNode verticeTeste = (TestNode)itt.next();
            if(cont1){
                carregarListaDeArestaDosTestes();
                cont1 = false;
            }
                listaConjuntoDeEtapas = new ArrayList<ConjuntoDeEtapas>();
               // Percorre todos os vertices das etapas
                for(Iterator itt2 = verticeTeste.getTodoscreen().getG().getVertices().iterator(); itt2.hasNext();){
                    ToDoNode verticeEtapa = (ToDoNode) itt2.next();
                   
                    ConjuntoDeEtapas conjuntoDeEtapas = new ConjuntoDeEtapas();
                    conjuntoDeEtapas.setId(verticeEtapa.getId());
                    conjuntoDeEtapas.setType(verticeEtapa.getType());
                    conjuntoDeEtapas.setCatid(verticeEtapa.getCatid());
                    conjuntoDeEtapas.setX(verticeEtapa.getX());
                    conjuntoDeEtapas.setY(verticeEtapa.getY());
                    conjuntoDeEtapas.setListaDeEtapa(verticeEtapa.getTodo().getListaDeEtapas());
                    conjuntoDeEtapas.setState(verticeEtapa.getState());
                    listaConjuntoDeEtapas.add(conjuntoDeEtapas);
                }
               
                Teste teste = new Teste();
                teste.setTitulo(verticeTeste.getJanelaDeDados().getNome());
                teste.setDescricaoTeste(verticeTeste.getJanelaDeDados().getDescricao());
                teste.setId(verticeTeste.getId());
                teste.setType(verticeTeste.getType());
                teste.setCatid(verticeTeste.getCatid());
                teste.setX(verticeTeste.getX());
                teste.setY(verticeTeste.getY());
                teste.setState(verticeTeste.getState());
                
                teste.setListaDoConjuntoDasEtapas(listaConjuntoDeEtapas);
                teste.setListaDasArestasDasEtapas(carregarListaDeArestaDasEtapas(verticeTeste.getTodoscreen().getG()));
                listaDeTestes.add(teste);
        }
        dadosMetodologia.setListaDeTestes(listaDeTestes);
        dadosMetodologia.setListaDasArestasDosTestes(listaDasArestasDosTestes);
    }
    
    private TestNode processarTestNode(int id){
        TestNode testNode = null;
        for(Iterator i = listadetestes.iterator(); i.hasNext();){
            TestNode teste = (TestNode)i.next();
            if(teste.getId() == id){
                testNode = teste;
            }
        }
        return testNode;
    }
    
    private DirectedSparseGraph<ToDoNode, String> processarToDoNode(Teste teste){
        g2 = new DirectedSparseGraph<ToDoNode, String>();
        ToDoNode etapa;
        for(Iterator i = teste.getListaDoConjuntoDasEtapas().iterator(); i.hasNext();){
            ConjuntoDeEtapas et = (ConjuntoDeEtapas)i.next();
            
            etapa = new ToDoNode(et.getId(), et.getType(), et.getCatid());
            etapa.setX(et.getX());
            etapa.setY(et.getY());
            etapa.setState(et.getState());
            etapa.getTodo().setListaDeEtapas(et.getListaDeEtapa());
            etapa.getTodo().carregarListaDeCheckBox();
            
             g2.addVertex(etapa);
        }
        
        ArrayList<Aresta> lista = teste.getListaDasArestasDasEtapas();
        for(Iterator i = lista.iterator(); i.hasNext();){
            Aresta aresta = (Aresta)i.next();
            ToDoNode origem = null, destino = null;
            for(Iterator it = g2.getVertices().iterator(); it.hasNext();){
                ToDoNode todo = (ToDoNode)it.next();
                if(aresta.getIdOrigem() == todo.getId()) origem = todo;
                if(aresta.getIdDestino() == todo.getId()) destino = todo;
            }
            g2.addEdge(aresta.getEdge(), origem, destino);
        }
        return g2;
    }
    
    public final void reloadGraphScreen() {
        TestNode testNode;
        Teste teste;
        
        for(Iterator i = dadosMetodologia.getListaDeTestes().iterator(); i.hasNext();){
            teste = (Teste)i.next();
            
            testNode = new TestNode(teste.getId(), teste.getType(), teste.getCatid());
            testNode.setX(teste.getX());
            testNode.setY(teste.getY());
            testNode.setState(teste.getState());
            testNode.getJanelaDeDados().setNome(teste.getTitulo());
            testNode.getJanelaDeDados().setDescricao(teste.getDescricaoTeste());
            testNode.getTodoscreen().setNovo(false);
            testNode.setG(processarToDoNode(teste)); // Só pra ver se presta (Testando função)
            testNode.getTodoscreen().setG(testNode.getG());
            testNode.getTodoscreen().reloadGraphScreen();
            g1.addVertex(testNode);
            listadetestes.add(testNode);
            if(teste.getType() == 0) start = testNode;
        }
        
        ArrayList<Aresta> lista = dadosMetodologia.getListaDasArestasDosTestes();
        for(Iterator i = lista.iterator(); i.hasNext();){
            Aresta aresta = (Aresta)i.next();
            g1.addEdge(aresta.getEdge(), processarTestNode(aresta.getIdOrigem()), processarTestNode(aresta.getIdDestino()));
        }
        
        layout.setGraph(g1);
        for (Iterator it = g1.getVertices().iterator(); it.hasNext();) {
            TestNode object = (TestNode) it.next();
            layout.setLocation(object, new Point2D.Double(object.getX(), object.getY()));
            //System.out.println(object.toString() + " " + object.getX() + " " + object.getY());
            if (object.getType() == 2) {
                nTests++;
            }
        }

        vv.setGraphLayout(layout);
        vv.getRenderContext().setVertexIconTransformer(
                new MyVertexIconTransformerLoadGraph<TestNode>());
        Factory<TestNode> vertexFactory = new JanelaAbrirMetodologia.VertexFactory();
        Factory<String> edgeFactory = new JanelaAbrirMetodologia.EdgeFactory();
        final EditingModalGraphMouse<TestNode, String> graphMouse =
                new EditingModalGraphMouse<TestNode, String>(vv.getRenderContext(), vertexFactory, edgeFactory);

        
        PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
        // Add some popup menus for the edges and vertices to our mouse plugin.
        JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu();

        JPopupMenu EdgeMenu = new MyMouseMenus.EdgeMenu();

        myPlugin.setVertexPopup(vertexMenu);
        myPlugin.setEdgePopup(EdgeMenu);
        graphMouse.remove(graphMouse.getPopupEditingPlugin());  // Removes the existing popup editing plugin

        graphMouse.add(myPlugin);   // Add our new plugin to the mouse

        vv.setGraphMouse(graphMouse);
        vv.addKeyListener(graphMouse.getModeKeyListener());

        graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
//        this.jComboBox1.setModel(graphMouse.getModeComboBox().getModel());
        //canCheck = true;
        //vv.repaint();
        nEdges = g1.getEdgeCount();
        nodecount = g1.getVertexCount();
        
        

        this.graphScroll.setViewportView(vv);
        zerarToolbar();
    }
    
}
